package org.university.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.university.entity.Course;
import org.university.repository.CourseRepository;
import org.university.service.CourseService;

@Service
public class CourseServiceImpl extends GenericServiceImpl<Course, String> implements CourseService {

    private static final Logger logger = LoggerFactory.getLogger(CourseServiceImpl.class);
    private final CourseRepository courseRepository;

    public CourseServiceImpl(CourseRepository repository, CourseRepository courseRepository) {
        super(repository);
        this.courseRepository = courseRepository;
    }

    @Override
    public Course save(Course course) {
        String id = course.getCourseId();
        logger.info("保存课程ID: {}", id);
        if (id != null && courseRepository.existsById(id)) {
            throw new IllegalArgumentException("课程ID已存在: " + id);
        }
        return courseRepository.save(course);
    }

    @Transactional
    public void update(String id, Course course) {
        if (id != null && !courseRepository.existsByCourseId(id)) {
            throw new IllegalArgumentException("更新课程ID不存在: " + id);
        }

        Course updateCourse = courseRepository.findByCourseId(id);

        updateCourse.setCourseId(id);
        updateCourse.setCourseType(course.getCourseType());
        updateCourse.setCourseName(course.getCourseName());
        updateCourse.setHours(course.getHours());
        updateCourse.setCredit(course.getCredit());
        updateCourse.setDescription(course.getDescription());

        courseRepository.save(updateCourse);
        logger.info("ID为 {} 的课程信息更新成功", course.getCourseId());
    }

    @Override
    public Page<Course> findAll(Pageable pageable) {
        logger.info("查询所有课程: 分页信息={}", pageable);
        return courseRepository.findByDeletedFalse(pageable);
    }

    @Override
    public Page<Course> findAll() {
        logger.info("查询所有课程（无分页）");
        return courseRepository.findByDeletedFalse(Pageable.unpaged());
    }

    @Override
    public void deleteById(String id) {
        logger.info("删除课程ID: {}", id);
        courseRepository.findById(id).ifPresent(course -> {
            course.setDeleted(1);
            courseRepository.save(course);
        });
    }
}